from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.db.models.functions import ExtractYear, ExtractMonth, ExtractDay
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import TemplateView
import datetime

from system.models import Router, UserProfile, ApplyAccount
from utils.common.common import transform_date
from utils.common.db_handle import get_all_account
from utils.common.tools import query_params
from custom import UnBindRouteView


@method_decorator(login_required, name='get')
class StatisticView(TemplateView):
    """统计页面"""

    template_name = 'backend/statistic.html'


@method_decorator(login_required, name='get')
class UserDetailView(View):
    """统计：用户详情表"""

    def get(self, request):
        one_year_ago = datetime.datetime.now() - datetime.timedelta(days=365)  # 一年前
        today = datetime.datetime.now().day  # 今天
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).day  # 昨天

        # 获取过去一年内每天的用户数目
        user_list = UserProfile.objects.filter(date_joined__gte=one_year_ago).annotate(
            year=ExtractYear('date_joined'), month=ExtractMonth('date_joined'), day=ExtractDay('date_joined')
        ).values('year', 'month', 'day').order_by('year', 'month', 'day').annotate(n=Count('id'))

        # 转换[{'date': '2020-1-11', 'nums': 1}, {'date': '2020-2-12', 'nums': 1}]
        user_list = transform_date(user_list)

        ret = {
            'user_list': user_list,
            'total': UserProfile.objects.all().count(),
            'today_nums': UserProfile.objects.filter(date_joined__day=today).count(),
            'yesterday_nums': UserProfile.objects.filter(date_joined__day=yesterday).count()
        }

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceDetailView(View):
    """统计：设备详情表"""

    def get(self, request):
        one_year_ago = datetime.datetime.now() - datetime.timedelta(days=365)  # 一年前
        today = datetime.datetime.now().day  # 今天
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).day  # 昨天

        # 获取过去一年内路由器设备的数目
        route_list = Router.objects.filter(create_time__gte=one_year_ago).annotate(
            year=ExtractYear('create_time'), month=ExtractMonth('create_time'), day=ExtractDay('create_time')
        ).values('year', 'month', 'day').order_by('year', 'month', 'day').annotate(n=Count('id'))
        route_list = transform_date(route_list)

        ret = {
            'route_list': route_list,
            'total': Router.objects.all().count(),
            'today_nums': Router.objects.filter(create_time__day=today).count(),
            'yesterday_nums': Router.objects.filter(create_time__day=yesterday).count()
        }

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class UserView(TemplateView):
    """用户视图"""
    template_name = 'backend/user_list.html'


@method_decorator(login_required, name='get')
class UserListView(View):
    """用户列表"""

    def get(self, request):
        condition = dict()
        fields = ['id', 'username', 'mobile', 'email', 'date_joined']
        username = request.GET.get("name")

        # 过滤查询
        if username:
            condition['username'] = username

        try:
            ret = dict(data=list(UserProfile.objects.filter(**condition).extra(
                select={"date_joined": "DATE_FORMAT(date_joined, '%%Y-%%m-%%d %%H:%%i:%%s')"}).values(*fields)))
        except Exception:
            ret = dict(data=list(UserProfile.objects.filter(**condition).values(*fields)))

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceView(TemplateView):
    """设备视图"""
    template_name = 'backend/device_list.html'


@method_decorator(login_required, name='get')
class DeviceListView(View):
    """设备列表"""

    def get(self, request):
        id = request.GET.get('id')
        draw = request.GET.get('draw')
        mac_addr = request.GET.get('mac_addr').strip()
        page = int(request.GET.get('page', 0))
        limit = int(request.GET.get('pagesize', 10))
        start, end = (page - 1) * limit, page * limit  # 计算要查询的数据数量

        fields = ['id', 'mac_addr', 'hmac_addr', 'server_addr', 'bind_time', 'user__username']
        ret = {'recordsFiltered': None, 'data': [], 'draw': draw, 'recordsTotal': 0}

        # 计算要查询的条件
        query_conditions = {'user_id': id, 'mac_addr': mac_addr}
        params = query_params(query_conditions)

        try:
            # 查询所有用户
            data = list(Router.objects.filter(**params).extra(
                select={"bind_time": "DATE_FORMAT(bind_time, '%%Y-%%m-%%d %%H:%%i:%%s')"}).values(*fields)[start: end])
        except Exception:
            data = list(Router.objects.filter(**params).values(*fields)[start:end])

        ret['data'] = data
        ret['recordsTotal'] = Router.objects.count()
        ret['recordsFiltered'] = len(data)

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceDeleteView(View):
    """删除设备"""

    def get(self, request):
        id = request.GET.get('id')
        route_obj = Router.objects.filter(id=id).first()
        ret = dict(status=False)
        try:
            # 解绑
            UnBindRouteView().unbind(request, route_obj)

            # 删除数据库中数据
            Router.objects.filter(id=id).delete()
            ret['status'] = True
        except Exception as e:
            pass

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceUpdateView(View):
    """解绑设备"""

    def get(self, request):
        id = request.GET.get('id')
        route_obj = Router.objects.filter(id=id).first()

        result = UnBindRouteView().unbind(request, route_obj)

        return JsonResponse(result)


@method_decorator(login_required, name='get')
class AuditView(TemplateView):
    """审核"""

    template_name = 'backend/audit.html'


@method_decorator(login_required, name='get')
class AuditListView(View):
    """审核、用户列表"""

    def get(self, request):
        condition = dict()
        draw = request.GET.get('draw')
        page = int(request.GET.get('page', 0))
        limit = int(request.GET.get('pagesize', 10))
        account_name = request.GET.get('account_name')
        start, end = (page - 1) * limit, page * limit  # 计算要查询的数据数量

        ret = {'recordsFiltered': None, 'data': [], 'draw': draw, 'recordsTotal': 0}

        # 过滤查询
        if account_name:
            condition['name'] = account_name

        user_list = get_all_account(condition, start, end)

        ret['data'] = user_list
        ret['recordsTotal'] = ApplyAccount.objects.count()
        ret['recordsFiltered'] = len(user_list)

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class AuditAccountView(View):
    """审核账户"""

    def get(self, request):
        ret = dict(results=False)
        id = request.GET.get('id')
        flag = request.GET.get('flag')

        try:
            if flag:
                ApplyAccount.objects.filter(id=id).update(status=2)  # 拒绝审核
            else:
                ApplyAccount.objects.filter(id=id).update(status=1)  # 审核

            ret['results'] = True
        except Exception as e:
            pass

        return JsonResponse(ret)
